package com.tank.net.msg;

import com.tank.DirectionEnum;
import com.tank.GroupEnum;
import com.tank.Tank;
import com.tank.TankFrame;

import java.io.*;
import java.util.UUID;

/**
 * @author CaoBaoYin
 * @since 21/11/4 16:12
 */
public class TankStoppedMsg extends Msg {
    private int x, y;
    private UUID id;

    public TankStoppedMsg() {
    }

    public TankStoppedMsg(Tank t) {
        this.x = t.getX();
        this.y = t.getY();
        this.id = t.getId();
    }

    @Override
    public byte[] toBytes() {
        byte[] bytes = null;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             DataOutputStream dos = new DataOutputStream(baos);) {

            dos.writeInt(this.x);
            dos.writeInt(this.y);
            dos.writeLong(id.getMostSignificantBits()); // 网络中没有人用字符串传输。会造成数据量大 这是128位的uuid，字符串128个字节，long只用了16个字节
            dos.writeLong(id.getLeastSignificantBits());
            dos.flush();

            bytes = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bytes;
    }

    @Override
    public void parse(byte[] bytes) {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             DataInputStream dis = new DataInputStream(bis)) {
            this.x = dis.readInt();
            this.y = dis.readInt();// 因为我们先写的x后写的y
            this.id = new UUID(dis.readLong(), dis.readLong());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void handle() {
        TankFrame tf = TankFrame.INSTANCE;
        // 如果是自己，不处理
        if (tf.getMainTank().getId().equals(this.id)) return;

        Tank tank = tf.tankMap.get(this.id);
        tank.setX(this.x);
        tank.setY(this.y);
        tank.setMoving(false);
    }

    @Override
    public MsgTypeEnum getMsgType() {
        return MsgTypeEnum.TANK_STOPPED;
    }

    @Override
    public String toString() {
        return "TankStoppedMsg{" +
                "x=" + x +
                ", y=" + y +
                ", id=" + id +
                '}';
    }
}
